package com.unity3d.networkapp9;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.security.auth.login.LoginException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView=findViewById(R.id.textView);

        /*网络在主线程异常-》网络请求不能在主线程
        生命周期中执行的方法默认时主线程（UI线程）不能执行耗时的操作
        耗时操作-》such as:
        读取文件（读数据库）、网络请求*/

        Log.i("MainActivity", "test1 ");
        Thread thread=new Thread(){
            @Override
            public void run() {
                //run()方法执行的代码都是在子线程中
                super.run();
                //网络请求
                try {
                    //请求服务器端
                    URL url = new URL("http://121.4.44.56/user");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");

                    //获取io输入字节流->字符流->缓存流
                    InputStream inputStream = urlConnection.getInputStream();// 字节流
                    Reader reader = new InputStreamReader(inputStream);//字符流
                    BufferedReader bufferedReader = new BufferedReader(reader);// 缓存流
                    //
                    String result = "";
                    String temp;
                    while ((temp = bufferedReader.readLine()) != null) {
                        result += temp;
                    }
                    Log.i("MainActivity", result);
                    Log.i("MainActivity", "test3 ");
                    //在子线程中设置文本
                    /*W/System.err: android.view.ViewRootImpl$CalledFromWrongThreadException:
                    Only the original thread that created a view hierarchy can touch its views.
                    对于UI控件的操作不能放在子线程中->需要放到主线程中执行->线程切换*/
                    //textView.setText(result);
                    //切换到主线程
                    String finalResult=result;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Gson gson=new Gson();
                            Student student=gson.fromJson(finalResult,Student.class);
                            //Log.i("MainActivity", "run: "+student.class1.classname);
                            Log.i("MainActivity", "run: "+student.students.get(0).name+" "+
                                    student.students.get(0).id);

                            // user
                            // json结构 本质性是一个字符串 ”key“:value { "age":30,"name":"张三", "isstudent":true }
                            //如何从json结构中解析出数据

                            /*object1
                            嵌套解析->json类型
                            { "age":20,"name":"张三", "isstudent":true,"class":{"grade":"18级","classname":"计算机科学与技术"} }
                            * */

                            /*object2
                            * { "grade":"18级","classname":"计算机科学与技术","students":["张三","李四","王五"] }
                            * 数组类型，josn类型，浮点型，整型，字符串型，布尔型 等等
                            * */

                            /*object3
                            *  { "grade":"18级","classname":"计算机科学与技术",
                            * "students":[
                            * { "id":"001","age":30,"name":"张三", "isstudent":false },
                            * { "id":"002","age":25,"name":"李四", "isstudent":true },
                            * { "id":"003","age":26,"name":"王五", "isstudent":true }
                            * ]}
                            * json数组*/
                            try {
                                JSONObject jsonObject=new JSONObject(finalResult);
                                String name=jsonObject.getString("name");
                                textView.setText(name);
                                /*JSONObject classObj=jsonObject.getJSONObject("class");
                                String className=classObj.getString("classname");
//                                String name=jsonObject.getString("name");
//                                textView.setText(name);
                                textView.setText(className);*/

                                /*JSONArray jsonArray= jsonObject.getJSONArray("students");
                                for(int i=0;i<jsonArray.length();++i){
                                    String student=jsonArray.getString(i);//根据下标获取
                                    Log.i("Students","student = "+student);
                                }*/

                                /*JSONArray jsonArray= jsonObject.getJSONArray("students");
                                for(int i=0;i<jsonArray.length();++i){
                                    JSONObject studentobj=jsonArray.getJSONObject(i);//根据下标获取
                                    String name=studentobj.getString("name");
                                    Integer age=studentobj.getInt("age");
                                    Log.i("MainActivity","name = "+name+" age = "+age);
                                }
*/
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            //textView.setText(finalResult);
                        }
                    });
                    inputStream.close();
                    reader.close();
                    bufferedReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        };
        thread.start();
        Log.i("MainActivity", "test2 ");
    }
}